package client;


import java.io.*;
import java.net.*;

import cmm.ConnectionInformation;

public abstract class Client implements IClient {

	private final static int ProxyConnectTimeout = 15*1000;	// value in ms = 15 Sec

	/**
	 * This method connects to the Proxy Server and retrieves the
	 * Connection Information of the Server to which the Client
	 * should connect to receive services. 
	 * 
	 * @param ProxyConnInfo - The Connection Information of the Proxy Server
	 * @return
	 * @throws IOException - Failure durring the connection to the Proxy Server 
	 * @throws ClassNotFoundException - Communication error with the Proxy Server
	 */
	protected static ConnectionInformation GetServerInfo(ConnectionInformation ProxyConnInfo) throws IOException, ClassNotFoundException{
		
		// Open a socket to the Proxy Server
		System.out.println("connecting to proxy to get a real server addr");
		System.out.println("Proxy addr: "+ProxyConnInfo.getIP().getHostAddress()+" port: "+ProxyConnInfo.getPort());
		
		Socket SocketToProxy = new Socket();
		SocketToProxy.connect(new InetSocketAddress(ProxyConnInfo.getIP(), ProxyConnInfo.getPort()), Client.ProxyConnectTimeout );
		// Open an input strean on the opened socket
		ObjectInputStream InStream = new ObjectInputStream(SocketToProxy.getInputStream());
		
		// Read Server Connection Info from the Input Stream
		System.out.println("reading data from proxy...");
		ConnectionInformation ServerConnInfo = (ConnectionInformation) InStream.readObject();
		System.out.println("Server Info: "+ServerConnInfo.getIP().getHostName()+" port: "+ServerConnInfo.getPort());
		
		// Close the connection to the Proxy Server
		InStream.close();
		SocketToProxy.close();
		
		return ServerConnInfo;
	}
	
}
